package org.hashdb.client.console.completer;

import jline.console.completer.Completer;
import org.hashdb.client.util.Strings;

import java.util.List;

/**
 * Date: 2024/1/11 20:36
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public class SupplierKeywordCompleter implements Completer, RemoteCompleter {
    @Override
    public int complete(String buffer, int cursor, List<CharSequence> candidates) {
        int whiteSpaceCount = 0;
        for (int i = buffer.length() - 1; i >= 0; i--) {
            if (Character.isWhitespace(buffer.charAt(i))) {
                ++whiteSpaceCount;
            }
        }

        var matchSource = Strings.trimRight(buffer);
        int curvesIndex = matchSource.lastIndexOf("(");
        if (matchSource.endsWith("|")) {
            return -1;
        }
        String prefix;
        if (curvesIndex != -1) {
            prefix = matchSource.substring(curvesIndex).toUpperCase();
        } else {
            prefix = matchSource.toUpperCase();
        }
        boolean matched = false;
        for (SupplierKeyword keyword : SupplierKeyword.values()) {
            if (keyword.name().startsWith(prefix)) {
                candidates.add(keyword.name());
                matched = true;
            }
        }
        return matched ? cursor - prefix.length() - whiteSpaceCount : -1;
    }
}
